package github.sf.fw.tools.db.impl;


import github.sf.fw.tools.db.AbstractDataSourceMeta;
import github.sf.fw.tools.db.DSProperty;
import github.sf.fw.tools.db.QueryFilter;
import github.sf.fw.tools.db.connector.JdbcConnector;
import github.sf.fw.tools.db.impl.mysql.MysqlConstants;
import github.sf.fw.tools.db.model.ResultRow;
import github.sf.fw.utils.StrUtil;

import java.sql.SQLException;
import java.util.List;

public abstract class RdbmsDataSourceMeta extends AbstractDataSourceMeta {

    public RdbmsDataSourceMeta(DSProperty dsProperty) {
        super(dsProperty);
    }

    public RdbmsDataSourceMeta(DSProperty dsProperty, QueryFilter<String> dbFilter) {
        super(dsProperty, dbFilter);
    }

    public List<ResultRow> doQuery(JdbcConnector jdbcConnector, String sql, Object[] args) {
        try {
            return jdbcConnector.doQuery(sql, args);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询某个数据库中的表
     *
     * @param jdbcConnector 数据库连接
     * @param schemaName    数据库名称
     * @return 表
     */
    public List<ResultRow> queryTables(JdbcConnector jdbcConnector, String schemaName) {
        return doQuery(jdbcConnector, MysqlConstants.QUERY_TABLE_INFO, new Object[]{schemaName});
    }

    public List<ResultRow> queryColumns(JdbcConnector jdbcConnector, String schemaName, String tableName) {
        return doQuery(jdbcConnector, MysqlConstants.QUERY_COLUMN_INFO, new Object[]{schemaName, tableName});
    }

    @Override
    public boolean checkTable(String tableName) {
        String sql = StrUtil.format("show tables like '{}'", tableName);
        try (JdbcConnector jdbcConnector = new JdbcConnector(dsProperty);) {
            List<ResultRow> resultRows = jdbcConnector.doQuery(sql, null);
            return resultRows != null && resultRows.size() > 0;
        } catch (SQLException e) {
            log.error("检测表格存在性出错", e);
            return false;
        }
    }
}
